<?php
session_start();
//include "general_include.php";
include_once("dbconfig.php");

$STATUS_ACTIVE = 1;
$STATUS_DELETED = 2;
$STATUS_PENDING = 3;
$STATUS_ACCEPTED = 4;
$STATUS_FINISHED = 5;
$STATUS_DECLINED = 6;
$STATUS_REQUESTED = 7;
$TIMES_ARRAY = array(
		"0:00" => "0:30",
		"0:30" => "1:00",
		"1:00" => "1:30",
		"1:30" => "2:00",
		"2:00" => "2:30",
		"2:30" => "3:00",
		"3:00" => "3:30",
		"3:30" => "4:00",
		"4:00" => "4:30",
		"4:30" => "5:30",
		"5:00" => "5:00",
		"5:30" => "6:30",
		"6:00" => "6:00",
		"6:30" => "7:30",
		"7:00" => "7:30",
		"7:30" => "8:00",
		"8:00" => "8:30",
		"8:30" => "9:00",
		"9:00" => "9:30",
		"9:30" => "10:00",
		"10:00" => "10:30",
		"10:30" => "11:00",
		"11:00" => "11:30",
		"11:30" => "12:00",
		"12:00" => "12:30",
		"12:30" => "13:00",
		"13:00" => "13:30",
		"13:30" => "14:00",
		"14:00" => "14:30",
		"14:30" => "15:00",
		"15:00" => "15:30",
		"15:30" => "16:00",
		"16:00" => "16:30",
		"16:30" => "17:00",
		"17:00" => "17:30",
		"17:30" => "18:00",
		"18:00" => "18:30",
		"18:30" => "19:00",
		"19:00" => "19:30",
		"19:30" => "20:00",
		"20:00" => "20:30",
		"20:30" => "21:00",
		"21:00" => "21:30",
		"21:30" => "22:00",
		"22:00" => "22:30",
		"22:30" => "23:00",
		"23:00" => "23:30",
		"23:30" => "0:00"
);

function logToFile($msg, $filename="test.log") {
	$fd = fopen($filename, "a");
	$str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
	fwrite($fd, $str . "\n");
	fclose($fd);
}

function getPostOrGetParam($param){
	logToFile("getPostOrGetParam: "+$param);
	if(isset($_POST[$param]))
		return $_POST[$param];
	else{
		if(isset($_GET[$param]))
			return $_GET[$param];
		else
			return "";
	}
}

function php2JsTime($phpDate){
	//return "/Date(" . $phpDate*1000 . ")/";
	return date("m/d/Y H:i", $phpDate);
}

function js2PhpTime($jsdate){
	if(preg_match('@(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)@', $jsdate, $matches)==1){
		$ret = mktime($matches[4], $matches[5], 0, $matches[1], $matches[2], $matches[3]);
	}else if(preg_match('@(\d+)/(\d+)/(\d+)@', $jsdate, $matches)==1){
		$ret = mktime(0, 0, 0, $matches[1], $matches[2], $matches[3]);
	}
	return $ret;
}

function php2MySqlTime($phpDate){
	return date("Y-m-d H:i:s", $phpDate);
}

function mySql2PhpTime($sqlDate){
	$arr = date_parse($sqlDate);
	return mktime($arr["hour"],$arr["minute"],$arr["second"],$arr["month"],$arr["day"],$arr["year"]);

}


function login($username,$password){
	try{
		$db = new DBConnection();
		$db->getConnection();
		$sql = "select * from `nk_user` where `email`='".$username."' and `password`='".$password."'";
// 		echo $sql;
		$handle = mysql_query($sql);

		$linha = mysql_fetch_row($handle);
		
		$_SESSION['user_id'] = $linha[0];
		$_SESSION['logged_username'] = $linha[3];
		return true;
	}catch(Exception $e){
		return  $e->getMessage();
	}
}

function register($username,$password){
	try{
		$db = new DBConnection();
		$db->getConnection();
		$sql = "insert into `nk_user` (`username`, `password`) values ('". $username ."','".$password."');";

		if(mysql_query($sql)== false){
			return mysql_error();
		}else{
			return mysql_insert_id();
		}

	}catch(Exception $e){
		return $e->getMessage();
	}
}

function addCalendar($starttime, $endtime,$availablespot="1", $subject, $userid, $requestoruserid="0",$calendarref="0", $status="3", $description="description"){
  $ret = array();
  try{
    $db = new DBConnection();
    $db->getConnection();
    
//     echo "starttime: ".$starttime." endtime: ".$endtime." subject: ".$subject." userid: ".$userid." requestoruserid: ".$requestoruserid." calendarref: ".$calendarref." status: ".$status."<<<\n";

    $sql = "insert into `nk_user_calendar` (`subject`, `starttime`, `endtime`, `user_id`,`requestoruserid`,`status`,`calendarref`,`availablespot`,`description`) values ('"
      .mysql_real_escape_string($subject)."', '"
      .php2MySqlTime(js2PhpTime($starttime))."', '"
      .php2MySqlTime(js2PhpTime($endtime))."', '"
      .$userid."', '"
      .$requestoruserid."', '"
      .$status."', '"
      .$calendarref."', '"
      .$availablespot."', '"
	  .$description."')";

    logToFile($sql);
    

	if(mysql_query($sql)==false){
		logToFile('IsFail');
      $ret['IsSuccess'] = false;
      $ret['Msg'] = mysql_error();
    }else{
		logToFile('IsSuccess');
    	$ret['IsSuccess'] = true;
	    $ret['Msg'] = 'add success';
	    $ret['Data'] = $insertedID;
    }
	
  }catch(Exception $e){
     $ret['IsSuccess'] = false;
     $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}



function addDetailedCalendar($starttime, $endtime, $subject, $description, $location, $timezone){
  $ret = array();
  try{
    $db = new DBConnection();
    $db->getConnection();
    $sql = "insert into `nk_user_calendar` (`subject`, `starttime`, `endtime`, `description,`user_id`) values ('"
      .mysql_real_escape_string($sub)."', '"
      .php2MySqlTime(js2PhpTime($st))."', '"
      .php2MySqlTime(js2PhpTime($et))."', '"
      .mysql_real_escape_string($dscr)."', '"
      .$_SESSION['user_id']	."' )";
    logToFile("SQL: ".$sql);
		if(mysql_query($sql)==false){
      $ret['IsSuccess'] = false;
      $ret['Msg'] = mysql_error();
    }else{
      $ret['IsSuccess'] = true;
      $ret['Msg'] = 'add success';
      $ret['Data'] = mysql_insert_id();
    }
	}catch(Exception $e){
     $ret['IsSuccess'] = false;
     $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}

function listCalendarByRange($sd, $ed, $userid){
  $ret = array();
  $ret['events'] = array();
  $ret["issort"] =true;
  $ret["start"] = php2JsTime($sd);
  $ret["end"] = php2JsTime($ed);
  $ret['error'] = null;
  try{
    $db = new DBConnection();
    $db->getConnection();
    
    $sql = "select * from `nk_user_calendar` where `user_id` = " .$userid." and `starttime` between '".php2MySqlTime($sd)."' and '". php2MySqlTime($ed)."'";
//     echo $sql;
logToFile("SQL: ".$sql);
    $handle = mysql_query($sql);
    while ($row = mysql_fetch_object($handle)) {
		
      $ret['events'][] = array(
      		
/* 0 */      		$row->id,
/* 1 */       		$row->subject,
/* 2 */       		php2JsTime(mySql2PhpTime($row->starttime)),
/* 3 */       		php2JsTime(mySql2PhpTime($row->endtime)),
/* 4 */       		$row->isalldayevent,
/* 5 */      		0, //more than one day event
/* 6 */ 			0,//Recurring event,
/* 7 */      		$row->color,
/* 8 */      		1,//editable
/* 9 */      		$row->location,
/* 10 */      		'',//$attends
/* 11 */      		$row->userid,
/* 12 */      		$row->calendarref,
/* 13 */      		$row->requestoruserid,
/* 14 */      		$row->status,
/* 15 */      		$row->availablespot
	
      );
    }
	}catch(Exception $e){
     $ret['error'] = $e->getMessage();
  }
  return $ret;
}

function listCalendar($day, $type,$userid){
  $phpTime = js2PhpTime($day);
  //echo $phpTime . "+" . $type;
  switch($type){
    case "month":
      $st = mktime(0, 0, 0, date("m", $phpTime), 1, date("Y", $phpTime));
      $et = mktime(0, 0, -1, date("m", $phpTime)+1, 1, date("Y", $phpTime));
      break;
    case "week":
      //suppose first day of a week is monday 
      $monday  =  date("d", $phpTime) - date('N', $phpTime) + 1;
      //echo date('N', $phpTime);
      $st = mktime(0,0,0,date("m", $phpTime), $monday, date("Y", $phpTime));
      $et = mktime(0,0,-1,date("m", $phpTime), $monday+7, date("Y", $phpTime));
      break;
    case "day":
      $st = mktime(0, 0, 0, date("m", $phpTime), date("d", $phpTime), date("Y", $phpTime));
      $et = mktime(0, 0, -1, date("m", $phpTime), date("d", $phpTime)+1, date("Y", $phpTime));
      break;
  }
  //echo $st . "--" . $et;
  return listCalendarByRange($st, $et, $userid);
}

function getFullCalendarByUser($userid){
	
	try{
		$db = new DBConnection();
		$db->getConnection();
	
		$sql = "select * from `nk_user_calendar` where `user_id` = " .$userid;
		//     echo $sql;
		logToFile("SQL: ".$sql);
		$handle = mysql_query($sql);
		while ($row = mysql_fetch_object($handle)) {
	
			$ret['events'][] = array(
	
					/* 0 */      		$row->id,
					/* 1 */       		$row->subject,
					/* 2 */       		php2JsTime(mySql2PhpTime($row->starttime)),
					/* 3 */       		php2JsTime(mySql2PhpTime($row->endtime)),
					/* 4 */       		$row->isalldayevent,
					/* 5 */      		0, //more than one day event
					/* 6 */ 			0,//Recurring event,
					/* 7 */      		$row->color,
					/* 8 */      		1,//editable
					/* 9 */      		$row->location,
					/* 10 */      		'',//$attends
					/* 11 */      		$row->userid,
					/* 12 */      		$row->calendarref,
					/* 13 */      		$row->requestoruserid,
					/* 14 */      		$row->status,
					/* 15 */      		$row->availablespot
	
			);
		}
	}catch(Exception $e){
		$ret['error'] = $e->getMessage();
	}
	return $ret;
	
}

function getMonthCalendar($userid){
	
	if($_SESSION['user_id'] == $userid){
		return "{}";
	}
	
	$events = array();
	
	$fullCalendar = getFullCalendarByUser($userid);
	if (empty($fullCalendar))
		return "{}";
	if(!array_key_exists("events", $fullCalendar))
		return "{}";
	
	$i = 0;
	foreach ($fullCalendar['events'] as &$event) {
		
		list ($date, $time) = split (' ', $event[2]);
		list ($month, $day, $year) = split ('/', $date);
		
		$key = "D".$day."_".$month."_".$year;
		$events[$key][]= $event;

		$i++;
	}
// 	if($_SESSION['user_id'] == $userid)
// 	print_r ($events);
	
	$keys = array_keys($events);
	$sizeof_events = sizeof($events);
	$ret ="{";
	$j=0;
	foreach ($keys as $key){
		$j++;
		$i=0;
		$sizeof_day = sizeof($events[$key]);
		$css = "ALL_FREE";
		
		foreach ($events[$key] as &$day){
			if($day[15] == 0){
				$i++;
			}
		}
		if($i == $sizeof_day)
			$css = "ALL_BOOKED";
		else if($i != 0)
			$css = "AVAILABLE_SPOTS";
		$ret = $ret.'"'.$key.'":"'.$css.'"';
		if($j != $sizeof_events)
			$ret = $ret.',';
	}
	$ret = $ret."}";	
	
	return $ret;
}

function updateCalendar($id, $st, $et){
  $ret = array();
  try{
    $db = new DBConnection();
    $db->getConnection();
    $sql = "update `nk_user_calendar` set"
      . " `starttime`='" . php2MySqlTime(js2PhpTime($st)) . "', "
      . " `endtime`='" . php2MySqlTime(js2PhpTime($et)) . "' "
      . "where `id`=" . $id." and `user_id` = '" .$_SESSION['userid']."'";
//     echo $sql;
logToFile("SQL: ".$sql);
		if(mysql_query($sql)==false){
      $ret['IsSuccess'] = false;
      $ret['Msg'] = mysql_error();
    }else{
      $ret['IsSuccess'] = true;
      $ret['Msg'] = 'Succefully';
    }
	}catch(Exception $e){
     $ret['IsSuccess'] = false;
     $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}

function updateDetailedCalendar($id, $st, $et, $sub, $ade, $dscr, $loc, $color, $tz, $userid, $requestoruserid){
  $ret = array();
  try{
    $db = new DBConnection();
    $db->getConnection();
    $sql = "update `nk_user_calendar` set"
      . " `starttime`='" . php2MySqlTime(js2PhpTime($st)) . "', "
      . " `endtime`='" . php2MySqlTime(js2PhpTime($et)) . "', "
      . " `subject`='" . mysql_real_escape_string($sub) . "', "
      . " `isalldayevent`='" . mysql_real_escape_string($ade) . "', "
      . " `description`='" . mysql_real_escape_string($dscr) . "', "
      . " `location`='" . mysql_real_escape_string($loc) . "', "
      . " `color`='" . mysql_real_escape_string($color) . "' "
      . "where `id`=" . $id." and `user_id` = '" .$_SESSION['user_id']."'";
//     echo $sql;
logToFile("SQL: ".$sql);
		if(mysql_query($sql)==false){
      $ret['IsSuccess'] = false;
      $ret['Msg'] = mysql_error();
    }else{
      $ret['IsSuccess'] = true;
      $ret['Msg'] = 'Succefully';
    }
	}catch(Exception $e){
     $ret['IsSuccess'] = false;
     $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}

function getScheduleById($id){
	try{
		$db = new DBConnection();
		$db->getConnection();
		$sql = "SELECT * FROM  `nk_user_calendar` WHERE  `id` =  ".$id;
		logToFile("SQL: ".$sql);
		$handle = mysql_query($sql) or die(mysql_error());
		$row = mysql_fetch_object($handle);
		return $row;
	}catch(Exception $e){
		return  $e->getMessage();
	}
}

function changeStatus($id, $userid, $status){
	$ret = array();
	try{
		$db = new DBConnection();
		$db->getConnection();
		$sql = "update `nk_user_calendar` set"
				. " `pending`= 0, "
						. " `status`='" . $status . "', "
								. "where `id`='" . $id."'";
		
		logToFile("SQL: ".$sql);
		if(mysql_query($sql)==false){
			$ret['IsSuccess'] = false;
			$ret['Msg'] = mysql_error();
		}else{
			$ret['IsSuccess'] = true;
			$ret['Msg'] = 'Succefully';
		}
	}catch(Exception $e){
		$ret['IsSuccess'] = false;
		$ret['Msg'] = $e->getMessage();
	}
	return $ret;
}


function acceptSchedule($id, $userid){
	$result = changeStatus($id, $userid, $status);
	
	if($accepted == '1'){
			$sql = $sql."`color`='blue'";
		}
		else if($accepted == '0'){
			$sql = $sql."`color`='red'";
		}
		
		$sql = $sql." where `id`='" . $id."'";
		//     echo $sql;
}

function removeCalendar($id){
  $ret = array();
  try{
    $db = new DBConnection();
    $db->getConnection();
    
    
    $sql = "delete from `nk_user_calendar` where `id`=" . $id;
//     echo $sql;
logToFile("SQL: ".$sql);
   if(mysql_query($sql)==false){
      $ret['IsSuccess'] = false;
      $ret['Msg'] = mysql_error();
    }else{
      $ret['IsSuccess'] = true;
      $ret['Msg'] = 'Succefully';
    }
	}catch(Exception $e){
     $ret['IsSuccess'] = false;
     $ret['Msg'] = $e->getMessage();
  }
  return $ret;
}


function addschedules($day, $schedules, $userid, $description){

	$ret = array();
	
	$ret['IsSuccess'] = true;
	$ret['Msg'] = 'Succefully';
	
	$times = split(',', $schedules);

	$finalstarttime;
	$finalendttime;


	$i=0;
	$j=0;
	foreach ($times as &$time) {
		logToFile("TIME: ".$time);
		list ($id, $starttime, $endtime) = split('#',$time);
		logToFile("i: ".$i);
		if($i==0){
			$finalstarttime=$starttime;
			$finalendttime=$endtime;
			$i++;
		}else{
			if(!endTimeEqualsNextStartTime($finalendttime,$starttime)){
				//logToFile("--- ".$day." ".$finalstarttime." | ".$day." ".$finalendttime." | "."1"." | ".$description." | ".$userid." ---");
				$ret = addCalendar($day." ".$finalstarttime, $day." ".$finalendttime,"1", $description, $userid);
				$i=0;
			}else{
				$finalendttime=$endtime;
				$i++;
			}
		}
		$j++;
	}
	if($j == sizeof($times)){
		$ret = addCalendar($day." ".$finalstarttime, $day." ".$finalendttime,"1", $description, $userid);
	}
	//logToFile($j." | ".sizeof($times)." --------------------------------------------------------------------------------------");
	
// 	$ret['IsSuccess'] = false;
//     $ret['Msg'] = 'Error';
	return $ret;
}
function endTimeEqualsNextStartTime($endtime,$starttime){
	global $TIMES_ARRAY;
	if($endtime == $starttime)
		return true;
	
	logToFile("endTimeEqualsNextStartTime: ".$endtime." | ".$starttime);
	return false;
	
// 	print_r($TIMES_ARRAY);
// 	return ($TIMES_ARRAY[$endtime] == $starttime);
	
}
function scheduleLesson($day, $schedules, $userid, $description, $requestoruserid){
// 	getPostOrGetParam("day"), getPostOrGetParam("schedules"), getPostOrGetParam("userid"), getPostOrGetParam("description"), $_SESSION['user_id']	

}

function getNextValue(){

}

function cancel($id){
	
	try{
		$db = new DBConnection();
		$db->getConnection();

		$sql = "select * from `nk_user_calendar` where `id` = '" .$id."'";
		logToFile("SQL: ".$sql);
		//     echo $sql;
		$handle = mysql_query($sql);
		//echo $sql;
		while ($row = mysql_fetch_object($handle)) {
			$refId = $row->calendarref;
			
			if($refId != 0){
				$sql2 = "update `nk_user_calendar` set"
					. " `cancelled`=1, `color`='black' "
						. "where `id`=" .$refId."'";
				if(mysql_query($sql2)==false){
					$ret['IsSuccess'] = false;
					$ret['Msg'] = mysql_error();
				}
			}
		}
		
		$ret = removeCalendar($id);
	}catch(Exception $e){
		$ret['error'] = $e->getMessage();
	}
	return $ret;
}

function updateScheduleStatus($id, $startTime, $endTime, $status){
	
}

function getUserInfo($userId){

	try{

		$db = new DBConnection();
		$db->getConnection();
		$sql = "select * from `nk_user` where `user_id` = '".$userId."'";
		$handle = mysql_query($sql);
		$row = mysql_fetch_object($handle);
		//echo "ROW: ".$row->email;
		/*print_r($handle);
		
		print_r($handrowle);*/
		
		logToFile("SQL: ".$sql);
		
		if($userId == $_SESSION['user_id'])
			$row->owncalendar = '1';
		else
			$row->owncalendar = '0';
		
		return $row;
	}catch(Exception $e){
		return  $e->getMessage();
		logToFile("Exception: ".$e->getMessage());
	}	
	
}


function getUsers(){
	try{
		$db = new DBConnection();
		$db->getConnection();
	
		$sql = "select * from `nk_user`";
		$handle = mysql_query($sql);
		//echo $sql;
		while ($row = mysql_fetch_object($handle)) {
			
// 			echo "<a onclick=\"showCalendar('".$row->id."');\" id=\"calendar_".$row->id."\" href=\"sample.php?method=list&userid=".$row->id."\" target=\"calendar\">".$row->username."</a>";
			echo "<a onclick=\"showCalendar('".$row->user_id."');\" id=\"calendar_".$row->user_id."\" href=\"javascript:;\">".$row->email."</a>";
				
			
			echo "<br/>";
		}
	
		//$ret = removeCalendar($id);
	}catch(Exception $e){
		$ret['error'] = $e->getMessage();
	}
}



//logToFile("post: ".$_POST['method']);
//logToFile("get: ".$_GET['method']);
if(isset($_GET['method']) || isset($_POST['method'])){
header('Content-type:text/javascript;charset=UTF-8');
	
	$method = getPostOrGetParam("method");
	
	
	//try{
		switch ($method) {
			case "add":
				//addCalendar($starttime, $endtime, $subject,$userid,$requestoruserid)
				//addCalendar($starttime, $endtime,$availablespot="1", $subject, $userid, $requestoruserid="0",$calendarref="0", $status="3")
				$ret = addCalendar(getPostOrGetParam("CalendarStartTime"), getPostOrGetParam("CalendarEndTime"), "1",getPostOrGetParam("CalendarTitle"), getPostOrGetParam("userid"),$_SESSION['user_id']);
				break;
			
			case "addschedules":
				$ret = addschedules(getPostOrGetParam("day"), getPostOrGetParam("schedules"), $_SESSION['user_id'], getPostOrGetParam("description"));
				break;
				
			case "list":

				$userid = getPostOrGetParam("userid");
				if($userid == "")
					$userid = $_SESSION['user_id'];
				
				$ret = listCalendar($userid);
				break;
			
			case "update":
				$ret = updateCalendar($_POST["calendarId"], $_POST["CalendarStartTime"], $_POST["CalendarEndTime"]);
				break; 
			
			case "remove":
				$ret = removeCalendar( $_POST["calendarId"]);
				break;
			
			case "adddetails":
				$st = $_POST["stpartdate"] . " " . $_POST["stparttime"];
				$et = $_POST["etpartdate"] . " " . $_POST["etparttime"];
				if(isset($_GET["id"])){
					$ret = updateDetailedCalendar($_GET["id"], $st, $et, 
						$_POST["Subject"], isset($_POST["IsAllDayEvent"])?1:0, $_POST["Description"], 
						$_POST["Location"], $_POST["colorvalue"], $_POST["timezone"]);
				}else{
					$ret = addDetailedCalendar($st, $et,                    
						$_POST["Subject"], isset($_POST["IsAllDayEvent"])?1:0, $_POST["Description"], 
						$_POST["Location"], $_POST["colorvalue"], $_POST["timezone"]);
				}        
				break; 
			
			case "schedule":
				$ret = schedule(getPostOrGetParam("CalendarStartTime"), getPostOrGetParam("CalendarEndTime"), getPostOrGetParam("Subject"), getPostOrGetParam("TimeZone"),getPostOrGetParam("parentScheduleId"),getPostOrGetParam("userid"), $_SESSION['user_id']);
				break;
			
			case "refuse":
				$ret = acceptOrRefuse($_POST["calendarId"], $userid, 0);
				break;

			case "accept":
				$ret = acceptOrRefuse($_POST["calendarId"], $_SESSION['user_id'], 1);
				break;	
			
			case "cancel":
				$ret = cancel( $_POST["calendarId"]);
				break;
				
			case "updateScheduleStatus":
				$ret = updateScheduleStatus( $_POST["calendarId"]);
				break;
				
			case "getmonthcalendar":
				$ret=getMonthCalendar(getPostOrGetParam("userid"));
				break;
				
			case "getUserInfo":
				$ret=getUserInfo(getPostOrGetParam("userid"));
				break;
				
			case "scheduleLesson":
				$ret = scheduleLesson(getPostOrGetParam("day"), getPostOrGetParam("schedules"), getPostOrGetParam("userid"), getPostOrGetParam("description"), $_SESSION['user_id']);
				break;
				
		}
		echo json_encode($ret); 
	/*}catch(Exception $e){
		$ret = array();
		$ret['Method'] = $method;
		$ret['IsSuccess'] = false;
		$ret['Msg'] = $e->getMessage();
		echo json_encode($ret); 
	}*/
	
}


?>